#指定cmake最小版本
cmake_minimum_required(VERSION 3.20)
#设置项目名称
project(cpp_example_01)

#使用的C++标准的版本
set(CMAKE_CXX_STANDARD 14)
#QT相关的搜索设置
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

#CMAKE_PREFIX_PATH设置一些包依赖包的搜索路径，常用在搜索.cmake配置文件
set(CMAKE_PREFIX_PATH "D:/Qt/5.15.2/msvc2019_64")

#设置项目需要的一些依赖包
find_package(Qt5 COMPONENTS
        Core
        REQUIRED)

#本项目是生成一个可执行文件，因此这里是add_executable，如果项目是生成库文件，则应该是add_library
#左边是生成可执行文件的名称，右边是需要编译成可执行文件所需要的源代码，包括cpp、h、hpp等
add_executable(cpp_example_01 main.cpp)
#指定可执行文件运行时需要依赖的dll库
target_link_libraries(cpp_example_01
        Qt5::Core
        )

#这是win下自动运行的一个脚本，可以将必要的QT中的dll库复制到exe所在目录
if (WIN32)
    set(DEBUG_SUFFIX)
    if (CMAKE_BUILD_TYPE MATCHES "Debug")
        set(DEBUG_SUFFIX "d")
    endif ()
    set(QT_INSTALL_PATH "${CMAKE_PREFIX_PATH}")
    if (NOT EXISTS "${QT_INSTALL_PATH}/bin")
        set(QT_INSTALL_PATH "${QT_INSTALL_PATH}/..")
        if (NOT EXISTS "${QT_INSTALL_PATH}/bin")
            set(QT_INSTALL_PATH "${QT_INSTALL_PATH}/..")
        endif ()
    endif ()
    if (EXISTS "${QT_INSTALL_PATH}/plugins/platforms/qwindows${DEBUG_SUFFIX}.dll")
        add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E make_directory
                "$<TARGET_FILE_DIR:${PROJECT_NAME}>/plugins/platforms/")
        add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy
                "${QT_INSTALL_PATH}/plugins/platforms/qwindows${DEBUG_SUFFIX}.dll"
                "$<TARGET_FILE_DIR:${PROJECT_NAME}>/plugins/platforms/")
    endif ()
    foreach (QT_LIB Core)
        add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy
                "${QT_INSTALL_PATH}/bin/Qt5${QT_LIB}${DEBUG_SUFFIX}.dll"
                "$<TARGET_FILE_DIR:${PROJECT_NAME}>")
    endforeach (QT_LIB)
endif ()
